package com.example.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.service.RedisService;
import com.example.demo.vo.user.UserInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {

    /**
     * 登录凭证存储(存储用户信息)
     */
    private final static String Login_Token = "demo:loginToken";
    /**
     * 过期时间
     */
    private final static int LoginToken_Expire = 7 * 60 * 60 * 24;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public UserInfo getUserInfo(String loginToken) {
        String str = get(Login_Token + ":" + loginToken);
        return !StringUtils.isEmpty(str) ? JSON.parseObject(str, UserInfo.class) : null;
    }

    @Override
    public void storeUserInfo(String loginToken, UserInfo userInfo) {
        String key = Login_Token + ":" + loginToken;
        set(key, JSONObject.toJSONString(userInfo), LoginToken_Expire);
    }

    @Override
    public void delLoginToken(String loginToken) {
        del(Login_Token + ":"+loginToken);
    }

    /**
     * 向redis存储值
     *
     * @param key
     * @param value
     * @param time  过期时间
     */
    private void set(String key, String value, long time) {
        stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    /**
     * 根据key从redis获取值
     *
     * @param key
     * @return
     */
    private String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    private boolean del(String key) {
        return stringRedisTemplate.delete(key);
    }

}
